const express = require("express");
const { File, sequelize } = require("../../models");
const { success, fail } = require("../../utils/response");
const { NotFound, BadRequest } = require("http-errors");
const { singleImgUpload, moreImgsUpload, ossSdk } = require("../../utils/aliyun-oss");
const { Op } = require("sequelize");
const router = express.Router();

// 查询文件-带分页
router.get("/", async (req, res) => {
  try {
    const { pageNum, pageSize } = req.query;
    const conditions = getConditions(req);
    const { count, rows } = await File.findAndCountAll(conditions);
    success(res, "获取成功", {
      pageNum,
      pageSize,
      count,
      list: rows,
    });
  } catch (error) {
    // console.log("自主抛出的错误！", error.name);
    fail(res, error);
  }
});
// 获取参数
function getConditions(req) {
  const { keywords, pageNum, pageSize } = req.query;
  const conditions = {
    where: {},
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (keywords) {
    conditions.where.originalname = {
      [Op.like]: `%${keywords}%`,
    };
  }
  return conditions;
}
// 上传单图片
router.post("/img", (req, res) => {
  singleImgUpload(req, res, async err => {
    try {
      if (err) {
        fail(res, err);
      } else {
        console.log("req.user", req.user);
        // if(!req.user?.userId) {
        //   throw new Unauthorized("请先登录");
        // }
        const param = {
          ...req.file,
          userId: req.user?.userId,
          fullName: req.file.path + req.file.filename,
        };
        const row = await File.create(param);
        success(res, "上传成功！", row);
      }
    } catch (error) {
      fail(res, error);
    }
  });
});
// 上传多图片
router.post("/imgs", (req, res) => {
  moreImgsUpload(req, res, async err => {
    try {
      if (err) {
        fail(res, err);
      } else {
        if(req.files && req.files.length>0) {
          for(let file of req.files) {
            const param = {
              ...file,
              userId: req.user?.userId,
              fullName: file.path + file.filename,
            };
            await File.create(param);
          }
        }
        success(res, "上传成功！", req.files);
      }
    } catch (error) {
      fail(res, error);
    }
  });
});
// 删除文件
router.delete("/:id", async (req, res) => {
  const transaction = await sequelize.transaction()
  try {
    const id = req.params.id;
    if (!id) {
      throw new BadRequest("缺少id");
    }
    const file = await File.findOne({
      where: {
        id: id,
      }
    })
    if(!file) {
      throw new NotFound("未找到此文件");
    }
    console.log('file==',file);

    const result = await ossSdk.delete(file.fullName)
    console.log('delete ali-oss result', result);
    // 删除成功：try块无异常 或者 result.res.status === 204
    const row = await file.destroy({
      transaction
    });
    await transaction.commit()
    success(res, "success",row);
  } catch (error) {
    await transaction.rollback()
    fail(res, error);
  }
});

// 批量删除文件
router.post("/deleteFiles", async (req, res) => {
  const transaction = await sequelize.transaction()
  try {
    const fileIds = req.body.fileIds;
    console.log('fileIds==',fileIds, Array.isArray(fileIds));
    if (!fileIds || !Array.isArray(fileIds)) {
      throw new BadRequest("缺少fileIds数组");
    }
    console.log('fileIds==',fileIds);
    
    const files = await File.findAll({
      attributes: ['id', 'fullName'],
      where: {
        id: {
          [Op.in]: fileIds
        },
      }
    })
    console.log('files==', files);
    
    if(!files || files.length == 0) {
      throw new NotFound("未找到此文件");
    }
    // console.log('file==',file);
    const fullNameArr = files.map(item => item.fullName || '')
    https://help.aliyun.com/zh/oss/developer-reference/nodejs-delete-objects?spm=a2c4g.11186623.0.0.215832efc0fFNC#concept-i1s-pc3-dhb
    await ossSdk.deleteMulti(fullNameArr, {quiet: true})
    
    // 删除成功：try块无异常 或者 result.res.status === 204
    const row = await File.destroy({
      where: {
        id: fileIds
      },
      transaction
    });
    // 提交事务
    await transaction.commit()
    success(res, "success",row);
  } catch (error) {
    // 回滚事务
    await transaction.rollback()
    fail(res, error);
  }
});

module.exports = router;
